﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace LordJS.Extensions
{
    public static class XmlSerializeUtil
    {
        public static string SerializeObjectToXml<T>(T obj)
        {
            //去除默认命名空间xmlns:xsd和xmlns:xsi
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("", "");

            XmlSerializer serializer = new XmlSerializer(typeof(T));
            
            // Create a TextWriter to hold the serialization.
            string xmlObj;
            using (TextWriter writer = new StringWriter())
            {
                serializer.Serialize(writer, obj, ns);
                xmlObj = writer.ToString();
            }

            return xmlObj;
        }

        public static T DeserializeXmlToObject<T>(string xmlObj)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            using (TextReader reader = new StringReader(xmlObj))
            {
                return (T)serializer.Deserialize(reader);
            }
        }
    }
}
